package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    GreenScan greenScan;
    @Autowired
    WmNewsMapper wmNewsMapper;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Override
    public void autoScanWmNews(Integer id) {
        // 1. 根据id查询自媒体文章数据
        WmNews wmNews = wmNewsMapper.selectById(id);
        // 2. 判断文章的状态是否为 1  (防止重复消费)
        if (wmNews.getStatus() != 1) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "当前不是待审核");
        }
        // 3. 开始审核
        // 3.0  抽取出 文章的所有文本内容  和  所有的图片路径
        Map<String, Object> contents = getContents(wmNews);
        // 3.1  DFA自管理的敏感词审核
        boolean scanSensitive = handleSensitive((String)contents.get("content"),wmNews);
        if (!scanSensitive){
            log.info("文章审核未通过，原因: 内容中包含敏感词");
            return;
        }
        // 失败  状态改为2   设置失败原因:
        // 通过  继续下一步
        // 3.2  阿里云内容安全文本审核
          boolean scanText = aliyunText((String)contents.get("content"),wmNews);
        if (!scanText){
            log.info("文章审核未通过，原因: 内容中包含敏感词");
            return;
        }
        // 失败  状态改为2   设置失败原因:
        // 待人工审核  状态改为3
        // 通过  继续下一步
        // 3.3  阿里云内容安全图片审
        boolean scanImage = aliyunImage((List<String>)contents.get("images"),wmNews);
        if (!scanImage){
            log.info("文章审核未通过，原因: 图片审核未通过");
            return;
        }
        // 失败  状态改为2   设置失败原因:
        // 待人工审核  状态改为3
        // 4.  如果全部审核通过，将文章状态改为8 审核通过
        updateWmNews(WmNews.Status.SUCCESS.getCode(), "审核通过",wmNews);
        // 5. TODO 根据文章的具体发布时间   发送延时发布消息
        long publishTime = wmNews.getPublishTime().getTime();
        long nowTime = System.currentTimeMillis();
        long remainTime = publishTime - nowTime;
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
        ,PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
        ,wmNews.getId()
        ,(message) -> {
              message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
              return message;
                });
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

    }

    /**
     * 阿里云审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean aliyunImage(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.imageUrlScan(images);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block":
                    // 失败
                    updateWmNews(WmNews.Status.FAIL.getCode(), "文章图片中违规信息: "+scanResult.getLabel() ,wmNews);
                    break;
                case "review":
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章图片中有不确定因素，需要进一步人工审核" ,wmNews);
                    break;
                case "pass":
                    // 成功
                    flag = true;
                    break;
                default:
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，需要进一步人工审核:" ,wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用失败，需要进一步人工审核:" ,wmNews);
        }
        return flag;
    }


    /**
     * 阿里云审核文字内容
     * @param content
     * @param wmNews
     * @return
     */
    private boolean aliyunText(String content, WmNews wmNews) {
        boolean flag = false;

        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block":
                    // 失败
                    updateWmNews(WmNews.Status.FAIL.getCode(), "文章内容中包含违规词汇: "+scanResult.getLabel() ,wmNews);
                    break;
                case "review":
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章内容中有不确定因素，需要进一步人工审核:" ,wmNews);
                    break;
                case "pass":
                    // 成功
                    flag = true;
                    break;
                default:
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，需要进一步人工审核:" ,wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用失败，需要进一步人工审核:" ,wmNews);
        }

        return flag;
    }

    /**
     * dfa敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        if (!sensitives.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        List<String> data = sensitives.getData();
        SensitiveWordUtil.initMap(data);
        Map<String, Integer> Imap = SensitiveWordUtil.matchWords(content);

        if (!CollectionUtils.isEmpty(Imap)){
            updateWmNews(WmNews.Status.FAIL.getCode(), "文章中包含敏感词: "+Imap ,wmNews);
            flag = false;
        }
        return flag;
    }

    /**
     * 封装响应
     * @param status
     * @param reason
     * @param wmNews
     */
    private void updateWmNews(Short status,String reason,WmNews wmNews){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    private Map<String, Object> getContents(WmNews wmNews) {
        Map<String, Object> result = new HashMap();
        String content = wmNews.getContent();
        List<Map> conmaps = JSON.parseArray(content, Map.class);

        String constr = conmaps.stream()
                .filter(m -> "text".equals(m.get("type")))
                .map(m -> m.get("value").toString())
                .collect(Collectors.joining("_hmtt_"));

        constr = wmNews.getTitle() + "_hmtt_" + constr;
        result.put("content", constr);

        List<String> images = conmaps.stream()
                .filter(m -> "image".equals(m.get("type")))
                .map(m -> m.get("value").toString())
                .collect(Collectors.toList());

        String coverStr = wmNews.getImages();
        if (StringUtils.isNotBlank(coverStr)) {
            List<String> coverImages = Arrays.stream(coverStr.split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            // 3.3  合并  内容图片 和  封面图片
            images.addAll(coverImages);}
            images = images.stream().distinct().collect(Collectors.toList());
            // 3.5  将所有图片 装入map
            result.put("images", images);
            return result;
        }
    }

